package com.ittony.controller;

import com.ittony.dto.SystemAdminDto;
import com.ittony.service.SystemAdminService;
import com.ittony.service.impl.SystemAdminServiceImpl;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;

@WebServlet("/account")
public class AccountServlet extends HttpServlet {

    private SystemAdminService systemAdminService = new SystemAdminServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        switch (method) {
            case "login":
                String username = req.getParameter("username");
                String password = req.getParameter("password");
                SystemAdminDto systemAdminDto = systemAdminService.login(username, password);
                switch (systemAdminDto.getCode()){
                    case -1:
                        req.setAttribute("usernameError", "Invalid username");
                        req.getRequestDispatcher("login.jsp").forward(req, resp);
                        break;
                    case -2:
                        req.setAttribute("passwordError", "Invalid password");
                        req.getRequestDispatcher("login.jsp").forward(req, resp);
                        break;
                    case 0:
                        HttpSession session = req.getSession();
                        session.setAttribute("systemAdmin",systemAdminDto.getSystemAdmin());
                        resp.sendRedirect("/systemadmin.jsp");
                        break;

                }
                break;
            case "logout":
                req.getSession().invalidate();
                resp.sendRedirect("/login.jsp");
                break;
        }

    }
}
